layui.define(["upload","element"],function(exports) {
	const upload = layui.upload;
	const element = layui.element;
	
	class myClass {
	 	constructor(opt){
            if($("#"+opt.id).length<1 ){ return $.alert(0,"容器id不存在"); }
            if(!opt.ywName ){ return $.alert(0,"业务名称不能为空"); }
            if(!opt.fkType ){ return $.alert(0," 附件类型不能为空"); }
            if(!opt.fkGuid ){ return $.alert(0," 附件主键不能为空"); }
            this.$el = $("#"+opt.id);
            this.option = opt || {};
            this.btnId =$.createGuid();
            this._initHtml();
        }
	 	
	 	get defaults (){ 
            let $th=this;
            let defaults={
            	multiple:true,
    			mode:1,
    			fkGuid:"",	
    			ywName: '',          			//必填，业务过程名称    
	            fkType:"",							//必填，附件类型
    			actionCode:0, 					 //按钮权限 0/1/2/3
    			errorInfo: 'fkGuid不存在', //fkGuid不存在时的报错信息,非必填
    			showType:"grid",             //列表展示方式: grid,paved
    			createBtn:true,
    			showSwiper:false,
    			min:0,
    			max:0,
    			accept:'file',		//允许上传的文件类型
            }
            return $.extend(true, {}, defaults, this.option);
        }
	 	
	 	_initHtml(){
	 		let $el = this.$el;
	 		let  actionCode = this.defaults.actionCode;
			let html=`
				<a href="javascript:;" class="fileUpload-link">相关附件(0)</a>
                <button type="button" class="fileUpload-btn"  id="${this.btnId}">上传附件</button>
			`;
			if(actionCode==3 ){
				html=`<a href="javascript:;" class="fileUpload-link">相关附件(0)</a>`;
			}
			if(this.defaults.createBtn){
				$el.addClass("fileUploadContainer").html(html);
				this._initSwiper();
				this._initEvemt();
	 			this.resetFileBtnCount();
			}else{
				$el.attr("id",this.btnId);
			}
	 		this._initUpload();
	 	}
	 	
	 	_initEvemt(){
	 		let that = this;
	 		let $el = this.$el;
	 		$el.find(".fileUpload-link").click(function(){
	 			let  defaults = that.defaults;
	 			defaults.url= __webConfig__.module+ "/views/system/upload/upload";
		        $.openWin(defaults, "上传列表",['800px', '450px']);
	 		});
	 		//删除图片
	 		$el.on("click",".fileUpload-deleteImg",function(){
	 		    let file_id  = $(this).attr("file_id");
	 		    let count = $el.find(".fileUpload-link").attr("count");
	 		    if(that.defaults.min > 0 && count <= that.defaults.min ){
	 		    	$.toast(0,"文件不能少于 "+ that.defaults.min);
	 		    	return false;
	 		    }
                $.confirm("确定删除图片？",function(){
                    $.ajaxs( __webConfig__.module +"/soft/upload/deleteFile", {
                        fileIds: file_id
                    }, function(res) {
                        $.toast(1, "删除成功！");
                        that.resetFileBtnCount();
                        if(that.deleteSuccessCallbackFn){
		                	that.deleteSuccessCallbackFn(res);
		                }
                    });
                });
            });
            //设置默认
	 		$el.on("click",".fileUpload-setDefault",function(){
	 		    let file_id  = $(this).attr("file_id");
	 		    let type  = $(this).attr("type");
                $.confirm( type == 0 ? "确定取消默认？" : "确定设置为默认图片？" ,function(){
                    $.ajaxs(__webConfig__.module +"/soft/upload/setDefault", {
                        file_id: file_id,
                        type:type
                    }, function(res) {
                        $.toast(1, "操作成功！");
                        that.resetFileBtnCount();
                    });
                });
            });
            //放大
	 		$el.on("click",".fileUpload-enlarge",function(){
	 		    $.openFullWin( __webConfig__.module +`/soft/upload/downloadhandler?file_id=`+$(this).attr("file_id"));
	 		});
	 	}
	 	
	 	_initSwiper(data){
	 		let that = this;
	 		if(this.initSwiperFrontCallbackFn){
            	data = this.initSwiperFrontCallbackFn(data);
            }
	 	    if(this.defaults.showSwiper){
	 	        this.$el.find('#fileUpload-carousel-'+this.option.id).remove();
	 	        var imgs = '';
	 	        if(data){
	 	            data.forEach(function(h){
	 	            	if(h.external_path){
	 	            		imgs += `<div style="background-image: url(${h.external_path});">`;
	 	            	}else{
	 	            		imgs += `<div style="background-image: url(${__root__}/${__webConfig__.module}/soft/upload/downloadhandler?file_id=${h.file_id});">`;
	 	            	}
	 	              	imgs+=`<i class="iconfont fileUpload-enlarge" file_id="${h.file_id}" title="全屏">&#xe658;</i>`;
	 	                if(that.defaults.actionCode != 3){
		 	                imgs+=`<i class="iconfont fileUpload-deleteImg" file_id="${h.file_id}" title="删除">&#xe68e;</i>`;
		 	                if(h.is_default){
		 	                	imgs+=`<i class="iconfont fileUpload-setDefault" file_id="${h.file_id}" title="取消默认" type="0" style="font-size: 20px;margin-top: 2px;">&#xe6bc;</i>`;
		 	                }else{
		 	                	imgs+=`<i class="iconfont fileUpload-setDefault" file_id="${h.file_id}" title="设为默认图片" type="1">&#xe678;</i>`;
		 	                }
	 	                }
	 	                imgs+="</div>";
	 	            });
	 	        }
                var html = `
                    <div class="layui-carousel fileUpload-layui-carousel" id="fileUpload-carousel-${this.option.id}">
                        <div carousel-item>${imgs}</div>
                    </div>
                `;
                this.$el.append(html);
                layui.carousel.render({
                    elem: '#fileUpload-carousel-'+this.option.id
                    ,width: '100%' //设置容器宽度
                    ,height: '150px' //设置容器宽度
                    ,arrow: 'always' //始终显示箭头always  hover none
                    ,indicator:'inside' //指示器 inside(容器内部) outside(容器外部) none
                    ,autoplay:false //是否自动切换
                    ,full:false  //是否全屏轮播
                });
            }
	 	    if(this.loadSuccessCallbackFn){
            	this.loadSuccessCallbackFn(data);
            }
	 	}
	 	
	 	_initUpload (){
	 		let that=this;
        	let defaults = this.defaults;
        	let layerIndex=null;
        	let timer = null;
        	upload.render({
			    elem:"#"+that.btnId,						//绑定元素
			    accept:defaults.accept || 'file',		//允许上传的文件类型
			    multiple:that.defaults.max == 1 ? false : true, //允许多文件上传
			    url: __webConfig__.module +'/soft/upload/upload' ,											//上传接口
			    number: that.defaults.max || 0,
			    auto: defaults.auto === false ? false : true,
			    bindAction:defaults.bindAction,
			    data:{
			    	fkGuid:defaults.fkGuid,			
	    			ywName: defaults.ywName,          
	    			fkType:defaults.fkType
			    },
			    clickBefore:function(){
			    	let count = that.$el.find(".fileUpload-link").attr("count");
		 		    if(that.defaults.max > 0 && count >= that.defaults.max ){
		 		    	$.toast(0,"文件数量不能大于 "+ that.defaults.max);
		 		    	return false;
		 		    }
			    },
			    before: function(obj){ 
			    	this.data.desc = $("#upload_textarea_info").val() || '';
			    	if(that.uploadBefore){
			    		this.data = that.uploadBefore(this.data) || this.data ;
			    	}
			    	let html=`
			    		<div class="layui-progress layui-progress-big"
			    			lay-filter="upload" 
			    			lay-showpercent="yes"
			    		>
			    		<div class="layui-progress-bar" lay-percent="0%"></div>
			    		</div>
			    	`;
			    	layerIndex = layer.open({
					  	type: 1,
					  	title: false,
					  	closeBtn : 0,
					  	skin: 'open-progress', //加上边框
					  	anim:-1, 
					  	isOutAnim:false,
					  	area: ['50%', '120px'], //宽高
					  	content: html,
					  	success: function(layero, index){
					  		element.render('progress'); 
					  		let n = 0;
					  		timer = setInterval(function(){
					        	n = n + Math.random()*10 | 0;  
					        	if(n>100){
					          		n = 100;
					          		clearInterval(timer);
					        	}
					        element.progress('upload', n+'%');
					      }, 100 + Math.random() *1000);
		  				}
					});
  				},
			   	done: function(resp,index,upload){
			   		if(resp.code == 0) {
			   			clearInterval(timer);
						setTimeout(function(){element.progress('upload', '100%'); },300);
						setTimeout(function(){ layer.close(layerIndex); },600);
						that.resetFileBtnCount();
					}else if(resp.code == -2){//错误 
	                   layer.close(layerIndex);
	                   $.alert(0, resp.msg);
	                }else if(resp.code == -10){//未登陆
	                	layer.close(layerIndex);
	                    $.alert(0, resp.msg,function(){
	                       window.location.href= window.location.href;
	                    });
	                }else{
	                	layer.close(layerIndex);
	                    $.alert(0, (resp.msg || "错误")+"<br/>"+resp.data);
	                }
	                if(that.uploadSuccessCallbackFn){
	                	that.uploadSuccessCallbackFn(resp);
	                }
			    },
			    error: function(index,upload){
			    	layer.close(layerIndex);
			    }
		  	});
        }
	 	
	 	//设置权限
	 	setActionCode(code){
	 		this.option.actionCode= code || 1;
	 		if(code=="3"){
	 			this.$el.find('.fileUpload-btn').hide();
	 		}else{
	 			this.$el.find('.fileUpload-btn').show();
	 		}
	 	}
	 	
	 	//刷新附件按钮数量
	 	resetFileBtnCount(){
	 	    let that = this;
	 		let $el = this.$el;
	 		let  defaults = this.defaults;
	 		let  param={
	 			fkGuid:defaults.fkGuid,			
    			ywName: defaults.ywName,          
    			fkType:defaults.fkType		   
	 		}
	 		$.ajaxs(__webConfig__.module +'/soft/upload/getFileList',param,function(res){
	 			let  count = (res.data && res.data.length) || 0;
	 			$el.find(".fileUpload-link").attr("count",count).text(`相关附件(${count})`);
	 			that._initSwiper( res.data );
	 		},true,false);
	 	}
	 	
		//获取附件列表	 	
	 	getFileList(){
	 		let  defaults = this.defaults;
	 		let  param={
	 			fkGuid:defaults.fkGuid,			
    			ywName: defaults.ywName,          
    			fkType:defaults.fkType		   
	 		}
	 		var fileList=[];
	 		$.ajaxs(__webConfig__.module +'/soft/upload/getFileList',param,function(res){ 
	 		    fileList = res.data || []; 
	 		},false);
	 		return fileList;
	 	}
	 	
	 	initSwiperFront(callbackFn){
	 		if(callbackFn){
	 			this.initSwiperFrontCallbackFn=callbackFn;
	 		}
	 	}
	 	
	 	loadSuccess(callbackFn){
	 		if(callbackFn){
	 			this.loadSuccessCallbackFn=callbackFn;
	 		}
	 	}
	 	
	 	uploadSuccess(callbackFn){
	 		if(callbackFn){
	 			this.uploadSuccessCallbackFn=callbackFn;
	 		}
	 	}
	 	
	 	deleteSuccess(callbackFn){
	 		if(callbackFn){
	 			this.deleteSuccessCallbackFn=callbackFn;
	 		}
	 	}
	 	
	 	//重置guid
	 	resetFkGuid(fkGuid){
	 		this.option.fkGuid =fkGuid;
    		this.resetFileBtnCount();
	 	}
	}
	
	exports('uploads',{
		init:function(opt){ 
			let uploadObj = new myClass(opt); 
			$(`#${opt.id}`).data("obj",uploadObj);
			return uploadObj;
		}
	});
});